/* dispatch异步提交 */
import { login, getInfo } from '@/api/login'
import { getToken, setToken, removeToken, getAccount, setAccount, removeAccount } from '@/utils/auth'
import { Message } from 'element-ui'

const user = {
  state: {
    token: getToken(),
    user: {},
    roles: [],
    // 第一次加载菜单时用到
    loadMenus: false,
    userId: getAccount()
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_USER: (state, user) => {
      state.user = user
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles
    },
    SET_LOAD_MENUS: (state, loadMenus) => {
      state.loadMenus = loadMenus
    },
    addAccount: (state, userId) => {
      state.userId = userId
    }
  },

  actions: {
    // 登录
    Login({ commit }, userInfo) {
      const userId = userInfo.userId
      const password = userInfo.password
      const rememberMe = userInfo.rememberMe
      return new Promise((resolve, reject) => {
        login(userId, password).then(res => {
          if (res.code === 2000 || res.code === '2000') {
            const color = localStorage.getItem('data')
            if (color == null || '') {
              commit('conmitColor', '#437985')
            }
            setToken(res.data.token, rememberMe)
            commit('SET_TOKEN', res.token)
            setAccount(userId)

            // setUserInfo(res.user, commit)
            // 第一次加载菜单时用到， 具体见 src 目录下的 permission.js
            commit('SET_LOAD_MENUS', true)
            location.reload()
            resolve()
          } else {
            Message.error({
              message: res.msg
            })
            reject('error')
          }
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 获取用户信息
    GetInfo({ commit }) {
      return new Promise((resolve, reject) => {
        getInfo().then(res => {         
          setUserInfo(res.data, commit)
          resolve(res.data)
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 登出
    LogOut({ commit }) {
      return new Promise((resolve, reject) => {
        commit('SET_TOKEN', '')
        commit('SET_ROLES', [])
        commit('addAccount', '')
        removeToken()
        removeAccount()
        resolve()
      })
    },

    updateLoadMenus({ commit }) {
      return new Promise((resolve, reject) => {
        commit('SET_LOAD_MENUS', false)
      })
    }
  }
}

export const setUserInfo = (res, commit) => {
  let  Ary = new Set(res.allPer)
  let  addRoles = getAccount()
  Ary.add(addRoles)
  if (addRoles === 'admin') {
    Ary.delete('sch_add')
    Ary.delete('sch_edit')
  }
  if (res.allPer.length === 0) {
    commit('SET_ROLES', ['ROLE_SYSTEM_DEFAULT'])
  } else {
    // commit('SET_ROLES', res.allPer)
    commit('SET_ROLES', [...Ary])
  }
  commit('SET_USER', res)
}

export default user
